<template>
  <div class="lost-item-page">
    <!-- 数据表格区域 -->
    <el-table :data="tableData" border stripe style="width: 100%;" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" />
      <el-table-column prop="lostId" label="失物ID" width="80" align="center" />
      <el-table-column prop="userId" label="用户ID" width="100" align="center" />
      <el-table-column prop="title" label="物品名称" align="center" />
      <el-table-column label="物品类型" align="center" width="100">
        <template #default="scope">
          {{ getCategoryName(scope.row.categoryId) }}
        </template>
      </el-table-column>
      <el-table-column label="物品状态" align="center" width="100">
        <template #default="scope">
          <el-tag :type="getStatusType(scope.row.status)">{{ getStatusName(scope.row.status) || '未知状态' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="images" label="物品图片" align="center">
        <template #default="scope">
          <el-image v-if="scope.row.images && scope.row.images.length > 0" :src="scope.row.images[0].url"
            style="width: 60px; height: 60px;" fit="cover" @click="handleImageClick(scope.row.images[0].url)" />
          <el-empty v-else description="无图片" />
        </template>
      </el-table-column>
      <el-table-column prop="lostTime" label="丢失时间" align="center">
        <template #default="scope">
          {{ formatDate(scope.row.lostTime) }}
        </template>
      </el-table-column>
      <el-table-column prop="contactWay" label="联系方式" align="center" />
      
      <!-- 详情操作列 -->
      <el-table-column label="详情操作" align="center" width="100">
        <template #default="scope">
          <el-button type="primary" icon="el-icon-view" size="small" @click="handleDetail(scope.row)">详情</el-button>
        </template>
      </el-table-column>
      
      <!-- 状态操作列 -->
      <el-table-column label="状态操作" align="center" width="160">
        <template #default="scope">
          <!-- 已下架状态显示上架按钮 -->
          <el-button v-if="scope.row.status === 4" 
            type="success"
            icon="el-icon-circle-plus"
            size="small"
            @click="handleOnline(scope.row)"
            :disabled="loading"
          >
            上架
          </el-button>
          <!-- 非已下架状态显示下架按钮 -->
          <el-button v-else 
            type="danger"
            icon="el-icon-circle-close"
            size="small"
            @click="handleOffline(scope.row)"
            :disabled="loading"
          >
            下架
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[10, 20, 50]"
      layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
      @current-change="handleCurrentChange" />
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import axios from 'axios'
import Swal from 'sweetalert2'
import 'sweetalert2/dist/sweetalert2.min.css'
import { ElMessage } from 'element-plus'
import { pa } from 'element-plus/es/locales.mjs'

// 配置API基础路径
const baseUrl = 'http://172.20.10.2:8080/api/LostItem'

// 状态管理
const loading = ref(false)
const tableData = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const selectedRows = ref([])

// 分类数据
const categoryOptions = ref([])

// 状态映射配置（2=未找回, 3=已找回, 4=已下架）
const statusMap = ref({
  2: { name: '未找回', type: 'warning' },
  3: { name: '已找回', type: 'success' },
  4: { name: '已下架', type: 'info' }
})

// 页面加载时获取数据
onMounted(() => {
  fetchCategoryData()
  fetchData()
})

// 获取分类数据
const fetchCategoryData = async () => {
  try {
    loading.value = true
    const response = await axios.get(`http://172.20.10.2:8080/api/Category/getAll`)
    if (response.data.code === 200) {
      categoryOptions.value = response.data.data || []
    } else {
      ElMessage.error(response.data.message || '获取分类数据失败')
    }
  } catch (error) {
    console.error('获取分类数据失败', error)
    ElMessage.error('网络错误，请稍后再试')
  } finally {
    loading.value = false
  }
}

// 获取失物列表
const fetchData = async () => {
  try {
    loading.value = true
    const response = await axios.get(`${baseUrl}/getAllPage`, {
      params: {
        page: currentPage.value,
        pageSize: pageSize.value
      }
    })

    if (response.data.code === 200) {
      tableData.value = response.data.data.list || []
      total.value = response.data.data.total || 0
    } else {
      ElMessage.error(response.data.message || '查询失败')
    }
  } catch (error) {
    console.error('查询失败', error)
    ElMessage.error('网络错误，请稍后再试')
  } finally {
    loading.value = false
  }
}

// 上架失物
const handleOnline = async (row) => {
  try {
    const result = await Swal.fire({
      title: '确认上架',
      text: `确定要将【${row.title}】重新上架吗？`,
      icon: 'warning',
      showCancelButton: true,
      confirmButtonColor: '#3085d6',
      cancelButtonColor: '#d33',
      confirmButtonText: '确定',
      cancelButtonText: '取消'
    })

    if (result.isConfirmed) {
      loading.value = true
      const response = await axios.put(`${baseUrl}/approve/${row.lostId}`, null,{
        params: {
          status: 2 // 状态设置为未找回
        }
      })

      if (response.data.code === 200) {
        ElMessage.success('上架成功')
        fetchData() // 刷新数据
      } else {
        ElMessage.error(response.data.message || '上架失败')
      }
    }
  } catch (error) {
    console.error('上架操作取消或失败', error)
  } finally {
    loading.value = false
  }
}

// 批量上架
const handleBatchOnline = async () => {
  const offlineRows = selectedRows.value.filter(row => row.status === 4)

  if (offlineRows.length === 0) {
    return ElMessage.warning('请选择需要上架的失物')
  }

  try {
    const result = await Swal.fire({
      title: '确认批量上架',
      text: `确定要将选中的${offlineRows.length}条失物重新上架吗？`,
      icon: 'warning',
      showCancelButton: true,
      confirmButtonColor: '#3085d6',
      cancelButtonColor: '#d33',
      confirmButtonText: '确定',
      cancelButtonText: '取消'
    })

    if (result.isConfirmed) {
      loading.value = true
      const ids = offlineRows.map(row => row.lostId)
      const response = await axios.put(`${baseUrl}/batchUpdateStatus`, {
        ids,
        status: 2
      })

      if (response.data.code === 200) {
        ElMessage.success('批量上架成功')
        fetchData()
        selectedRows.value = []
      } else {
        ElMessage.error(response.data.message || '批量上架失败')
      }
    }
  } catch (error) {
    console.error('批量上架操作取消或失败', error)
  } finally {
    loading.value = false
  }
}

// 下架失物
const handleOffline = async (row) => {
  try {
    const result = await Swal.fire({
      title: '确认下架',
      text: `确定要将【${row.title}】标记为已下架吗？`,
      icon: 'warning',
      showCancelButton: true,
      confirmButtonColor: '#3085d6',
      cancelButtonColor: '#d33',
      confirmButtonText: '确定',
      cancelButtonText: '取消'
    })

    if (result.isConfirmed) {
      loading.value = true
      const response = await axios.put(`${baseUrl}/reject/${row.lostId}`,null, {
        params: {
          status: 4 // 设置为已下架状态
        }
        
      })

      if (response.data.code === 200) {
        ElMessage.success('下架成功')
        fetchData() // 刷新数据
      } else {
        ElMessage.error(response.data.message || '下架失败')
      }
    }
  } catch (error) {
    console.error('下架操作取消或失败', error)
  } finally {
    loading.value = false
  }
}

// 批量下架
const handleBatchOffline = async () => {
  const onlineRows = selectedRows.value.filter(row => row.status !== 4)

  if (onlineRows.length === 0) {
    return ElMessage.warning('请选择需要下架的失物')
  }

  try {
    const result = await Swal.fire({
      title: '确认批量下架',
      text: `确定要将选中的${onlineRows.length}条失物标记为已下架吗？`,
      icon: 'warning',
      showCancelButton: true,
      confirmButtonColor: '#3085d6',
      cancelButtonColor: '#d33',
      confirmButtonText: '确定',
      cancelButtonText: '取消'
    })

    if (result.isConfirmed) {
      loading.value = true
      const ids = onlineRows.map(row => row.lostId)
      const response = await axios.put(`${baseUrl}/batchUpdateStatus`, {
        ids,
        status: 4
      })

      if (response.data.code === 200) {
        ElMessage.success('批量下架成功')
        fetchData()
        selectedRows.value = []
      } else {
        ElMessage.error(response.data.message || '批量下架失败')
      }
    }
  } catch (error) {
    console.error('批量下架操作取消或失败', error)
  } finally {
    loading.value = false
  }
}

// 详情查看
const handleDetail = (row) => {
  try {
    // 构建详情内容
    const detailHTML = `
      <div class="swal-detail">
        <h3 style="margin-bottom: 20px; color: #333;">失物详情</h3>
        <div class="swal-item" style="display: flex; margin-bottom: 15px; padding-bottom: 15px; border-bottom: 1px solid #ebeef5;">
          <span class="swal-label" style="min-width: 80px; color: #606266; font-weight: 500;">失物ID:</span>
          <span class="swal-value" style="color: #303133;">${row.lostId}</span>
        </div>
        <div class="swal-item" style="display: flex; margin-bottom: 15px; padding-bottom: 15px; border-bottom: 1px solid #ebeef5;">
          <span class="swal-label" style="min-width: 80px; color: #606266; font-weight: 500;">用户ID:</span>
          <span class="swal-value" style="color: #303133;">${row.userId}</span>
        </div>
        <div class="swal-item" style="display: flex; margin-bottom: 15px; padding-bottom: 15px; border-bottom: 1px solid #ebeef5;">
          <span class="swal-label" style="min-width: 80px; color: #606266; font-weight: 500;">物品名称:</span>
          <span class="swal-value" style="color: #303133;">${row.title}</span>
        </div>
        <div class="swal-item" style="display: flex; margin-bottom: 15px; padding-bottom: 15px; border-bottom: 1px solid #ebeef5;">
          <span class="swal-label" style="min-width: 80px; color: #606266; font-weight: 500;">物品类型:</span>
          <span class="swal-value" style="color: #303133;">${getCategoryName(row.categoryId)}</span>
        </div>
        <div class="swal-item" style="display: flex; margin-bottom: 15px; padding-bottom: 15px; border-bottom: 1px solid #ebeef5;">
          <span class="swal-label" style="min-width: 80px; color: #606266; font-weight: 500;">物品状态:</span>
          <span class="swal-value"><span class="swal-tag" style="display: inline-block; padding: 2px 8px; border-radius: 4px; color: white; ${getStatusType(row.status) === 'warning' ? 'background-color: #909399;' : getStatusType(row.status) === 'success' ? 'background-color: #67c23a;' : 'background-color: #409EFF;'}">${getStatusName(row.status) || '未知状态'}</span></span>
        </div>
        <div class="swal-item" style="display: flex; margin-bottom: 15px; padding-bottom: 15px; border-bottom: 1px solid #ebeef5;">
          <span class="swal-label" style="min-width: 80px; color: #606266; font-weight: 500;">丢失时间:</span>
          <span class="swal-value" style="color: #303133;">${formatDate(row.lostTime)}</span>
        </div>
        <div class="swal-item" style="display: flex; margin-bottom: 15px; padding-bottom: 15px; border-bottom: 1px solid #ebeef5;">
          <span class="swal-label" style="min-width: 80px; color: #606266; font-weight: 500;">丢失地点:</span>
          <span class="swal-value" style="color: #303133;">${row.lostLocation || '未填写'}</span>
        </div>
        <div class="swal-item" style="display: flex; margin-bottom: 15px; padding-bottom: 15px; border-bottom: 1px solid #ebeef5;">
          <span class="swal-label" style="min-width: 80px; color: #606266; font-weight: 500;">联系方式:</span>
          <span class="swal-value" style="color: #303133;">${row.contactWay || '未填写'}</span>
        </div>
        <div class="swal-item" style="display: flex; margin-bottom: 15px; padding-bottom: 15px; border-bottom: 1px solid #ebeef5;">
          <span class="swal-label" style="min-width: 80px; color: #606266; font-weight: 500;">物品描述:</span>
          <div class="swal-description" style="margin-top: 5px; color: #303133; line-height: 1.5; white-space: pre-wrap;">${row.description || '无描述信息'}</div>
        </div>
        
        <!-- 图片展示 -->
        <div class="swal-images" style="width: 100%; margin-top: 20px;" ${row.images && row.images.length > 0 ? '' : 'style="display: none;"'}>
          <h4 style="margin: 20px 0 10px; color: #333;">物品图片</h4>
          <div class="swal-image-list" style="display: flex; flex-wrap: wrap;">
            ${row.images && row.images.length > 0 ? row.images.map(img => `
              <div class="swal-image-item" style="margin-right: 10px; margin-bottom: 10px;">
                <img src="${img.url}" alt="物品图片" style="width: 120px; height: 120px; object-fit: cover; border-radius: 4px; cursor: pointer;" onclick="window.showImage('${img.url}')">
              </div>
            `).join('') : ''}
          </div>
        </div>
        <div class="swal-no-image" style="width: 100%; margin-top: 20px;" ${row.images && row.images.length > 0 ? 'style="display: none;"' : ''}>
          <div style="padding: 15px; border: 1px dashed #ebeef5; border-radius: 4px; text-align: center; color: #909399;">
            <i class="el-icon-picture-outline" style="font-size: 24px; margin-bottom: 10px; display: block;"></i>
            <span>无图片信息</span>
          </div>
        </div>
      </div>
    `

    // 显示详情弹窗
    Swal.fire({
      title: '失物详情',
      html: detailHTML,
      width: '800px',
      padding: '2rem',
      backdrop: `
        rgba(0, 0, 0, 0.4)
      `,
      showCancelButton: true,
      confirmButtonColor: '#409EFF',
      cancelButtonText: '关闭',
      confirmButtonText: '关闭',
      preConfirm: () => {
        return true
      },
      didOpen: () => {
        // 定义图片查看函数
        window.showImage = (url) => {
          Swal.fire({
            title: '图片预览',
            html: `<img src="${url}" style="max-width: 800px; max-height: 600px; object-fit: contain;">`,
            width: '900px',
            padding: '0',
            backdrop: `
              rgba(0, 0, 0, 0.8)
            `,
            showCancelButton: true,
            cancelButtonColor: '#aaa',
            cancelButtonText: '关闭',
            confirmButtonColor: '#409EFF',
            confirmButtonText: '关闭',
            preConfirm: () => {
              return true
            }
          })
        }
      }
    })
  } catch (error) {
    console.error('查看详情失败', error)
    ElMessage.error('查看详情失败，请稍后再试')
  }
}

// 查看单张图片
const handleImageClick = (url) => {
  Swal.fire({
    title: '图片预览',
    html: `<img src="${url}" style="max-width: 800px; max-height: 600px; object-fit: contain;">`,
    width: '900px',
    padding: '0',
    backdrop: `
      rgba(0, 0, 0, 0.8)
    `,
    showCancelButton: true,
    cancelButtonColor: '#aaa',
    cancelButtonText: '关闭',
    confirmButtonColor: '#409EFF',
    confirmButtonText: '关闭',
    preConfirm: () => {
      return true
    }
  })
}

// 选择行变化
const handleSelectionChange = (val) => {
  selectedRows.value = val
}

// 工具方法
const getCategoryName = (categoryId) => {
  const category = categoryOptions.value.find(c => c.categoryId === categoryId)
  return category ? category.categoryName : '未分类'
}

const getStatusType = (status) => {
  return statusMap.value[status]?.type || 'default'
}

const getStatusName = (status) => {
  return statusMap.value[status]?.name || '未知状态'
}

const formatDate = (dateStr) => {
  if (!dateStr) return '-'
  const date = new Date(dateStr)
  return date.toLocaleString()
}

// 分页相关方法
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchData()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchData()
}
</script>

<style scoped>
.lost-item-page {
  padding: 20px;
}

.el-image {
  cursor: pointer;
}

.el-button--primary {
  background-color: #409EFF;
  border-color: #409EFF;
}

.el-button--primary:hover {
  background-color: #3a8ee6;
  border-color: #3a8ee6;
}

.el-button--danger {
  background-color: #f56c6c;
  border-color: #f56c6c;
}

.el-button--danger:hover {
  background-color: #f45454;
  border-color: #f45454;
}

.el-button--success {
  background-color: #67c23a;
  border-color: #67c23a;
}

.el-button--success:hover {
  background-color: #5daf34;
  border-color: #5daf34;
}

.el-table__row:hover {
  background-color: #f5f7fa;
}

.el-pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.offline-tip {
  color: #909399;
  font-size: 12px;
}
</style>